﻿using System;
using System.Text;
using System.IO;
using System.Collections.Generic;

namespace ThumbcacheHelper
{
    static class Utils
    {
        /// <summary>
        /// Converts a byte[] into a string of bytes. Eg: byte[] { 0xFA, 0xCE } => "FACE"
        /// </summary>
        /// <param name="Source">byte array to convert</param>
        /// <returns>Concatenated byte values</returns>
        public static string ByteArrayToByteString(byte[] Source)
        {
            if (Source == null || Source.Length < 1)
                return null;

            StringBuilder sb = new StringBuilder();
            foreach (byte b in Source)
            {
                sb.Append(b.ToString("X2"));
            }
            return sb.ToString();
        }

        /// <summary>
        /// Checks that there are enough bytes left in the stream to read before reading.
        /// </summary>
        /// <param name="br">The BinaryReader which will be read</param>
        /// <param name="count">The number of bytes required</param>
        /// <returns>The bytes read or a EndOfStreamException is thrown</returns>
        public static byte[] AssuredReadBytes(BinaryReader br, int count)
        {
            if ((br.BaseStream.Position + count) > br.BaseStream.Length)
            {
                throw new EndOfStreamException();
            }

            return br.ReadBytes(count);
        }

        public static bool ArrayStartsWith<T>(T[] haystack, T[] needle)
        {
            bool result = true;

            if (needle.Length > haystack.Length)
            {
                result = false;
            }
            else
            {
                for (int i = 0; i < needle.Length; i++)
                {
                    if (!EqualityComparer<T>.Default.Equals(haystack[i], needle[i]))
                    {
                        result = false;
                        break;
                    }
                }
            }

            return result;
        }
    }
}
